import 'dart:async';

import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../json/datalog.dart';
import '../json/message.dart';

class PumpPage extends StatefulWidget {
  @override
  _PumpPageState createState() => _PumpPageState();
}

class _PumpPageState extends State<PumpPage> {

  var url = "http://175.178.187.21:18000";  //本地环境 https://188l877k45.zicp.vip  //生产环境 http://175.178.187.21:18000
  //var produce = url+"";   //生产环境

  List<Message?> message = [];

  List<Datalog?> dataLog = [];

  //Map address = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
   // getAddress();
    int _count = 0;
    Timer.periodic(const Duration(seconds: 5), (timer) {
      _count++;
      //print('count: $_count');
      if (_count == 30) {

        //清除定时器
        timer.cancel();
        _count = 0;
      }

      //获取当前是否已连接
      getMessage();

      //获取当前连接的数据以及操作指令
      getLogData();
    });
  }


  //获取连接信息
  void getMessage() async {
    var result =
    await new Dio().post(url+"/iot/data/desc");
    var time = result.data[0]["createTime"];
    DateTime nettime = DateTime.parse(time);
    //print(formatDate(nettime,[nettime.year,'年',nettime.month,'月',nettime.day]));
    //print(formatDate(DateTime.parse(time), [DateTime.parse(time).year.toString(),'年',DateTime.parse(time).month.toString(),'月',DateTime.parse(time).day.toString()+"日",' ',DateTime.parse(time).hour.toString(),':',DateTime.parse(time).minute.toString()]));

    // print(formatDate(_nowDate,[yyyy,'年',mm,'月',dd,' ',HH,':',nn]))
    List<Message?> list = (result.data as List<dynamic>)
        .map((e) => Message.fromMap((e as Map<String, dynamic>)))
        .toList();

    setState(() {
      message = list;
    });
  }

  //获取操作指令日志
  void getLogData() async {
    var result =
    await new Dio().post(url+"/iot/log/data/1/10");
    var time = result.data["records"][0]["create_time"];
    var data1 = result.data["records"][0]["iot_data"];
    DateTime nettime = DateTime.parse(time);
    var timesss = formatDate(nettime, [
      nettime.year.toString(),
      '-',
      nettime.month.toString(),
      '-',
      nettime.day.toString(),
      ' ',
      HH,
      ':',
      nn
    ]);
    print(1);

    List<Datalog?> list = (result.data["records"] as List<dynamic>)
        .map((e) => Datalog.fromMap((e as Map<String, dynamic>)))
        .toList();
    setState(() {
      dataLog = list;
    });
  }

  //启动
  void getstart() async {
    var result =
    await new Dio().post(url+"/emqxPublish/a");
    print("aaaaaaaa");
  }


  //停止
  void centerstop() async {
    var result =
    await new Dio().post(url+"/emqxPublish/b");
    print("bbbbbbbb");
  }

  //减速
  void moderate() async {
    var result =
    await new Dio().post(url+"/emqxPublish/c");
    print("ccccccc");
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    message.clear();
    dataLog.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("浇花"),
        centerTitle: true,
      ),
      body: Container(
        decoration: BoxDecoration(gradient: LinearGradient(
          colors: [
            Colors.red,
            Colors.orange,
            Colors.yellow,
            Colors.green,
            Colors.deepOrangeAccent,
            Colors.blue,
            Colors.purple
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        )),
        child: Padding(
          padding: EdgeInsets.only(top: 50),

            child: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              //decoration: BoxDecoration(color: Colors.lightBlueAccent),
              child: Column(

                children: [
                  //SizedBox(height: 10,),
                  Text(
                      "" +
                          formatDate(
                            DateTime.parse(message[0]!.createTime.toString()),
                            [
                              DateTime.parse(message[0]!.createTime.toString())
                                  .month
                                  .toString(),
                              '月',
                              DateTime.parse(message[0]!.createTime.toString())
                                  .day
                                  .toString() +
                                  "日",
                              ' ',
                              HH,
                              ':',
                              nn
                            ],
                          )+" -连接成功"
                      //+"--"+e.iotData == 2 ? "前进":e.iotData == 3 ? "后退":e.iotData == 4 ?"左转":e.iotData == 5 ?"右转":e.iotData == 6?"停止":e.iotData == 7?"加速":"减速"
                      ,style: TextStyle(fontSize: 12)),
                  SizedBox(height: 16,),

                    Container(
                      child: new Material(
                      color:Colors.transparent,
                        child: new Ink(
                          //设置背景
                          decoration: new BoxDecoration(
                            //背景
                            color: Colors.lightBlueAccent,
                            //设置四周圆角 角度
                            borderRadius: BorderRadius.all(Radius.circular(100.0)),
                            //设置四周边框
                            border: new Border.all(width: 3, color: Colors.blue),
                          ),
                          child: new InkResponse(
                            borderRadius: new BorderRadius.all(new Radius.circular(100.0)),
                            //点击或者toch控件高亮的shape形状
                            highlightShape: BoxShape.rectangle,
                            radius: 100.0,
                            //水波纹的颜色
                            splashColor: Colors.deepOrange,
                            //true表示要剪裁水波纹响应的界面 false不剪裁 如果控件是圆角不剪裁的话水波纹是矩形
                            containedInkWell: true,
                            //点击事件
                            onTap: () {
                              getstart();
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                //color: Colors.deepOrange,
                                  borderRadius: BorderRadius.circular(100),
                                  boxShadow: [
                                    BoxShadow(
                                        offset: Offset(1, 1),//x,y轴
                                        color: Colors.blueAccent,//投影颜色
                                        blurRadius: 10//投影距离
                                    )
                                  ]

                              ),
                              //设置 child 居中
                              alignment: Alignment(0, 0),
                              height: 100.0,
                              width: 100,
                              child: Text("启动浇水",style: TextStyle(fontSize: 15,fontWeight: FontWeight.w800,color: Colors.white),),
                            ),
                          ),
                        ),
                      ),

                  ),
                  SizedBox(height: 30,),

                    Container(
                      child: new Material(
                        color:Colors.transparent,
                        child: new Ink(
                          //设置背景
                          decoration: new BoxDecoration(
                            //背景
                            color: Colors.amberAccent,
                            //设置四周圆角 角度
                            borderRadius: BorderRadius.all(Radius.circular(100.0)),
                            //设置四周边框
                            border: new Border.all(width: 3, color: Colors.blue),
                          ),
                          child: new InkResponse(
                            borderRadius: new BorderRadius.all(new Radius.circular(100.0)),
                            //点击或者toch控件高亮的shape形状
                            highlightShape: BoxShape.rectangle,
                            radius: 100.0,
                            //水波纹的颜色
                            splashColor: Colors.blue,
                            //true表示要剪裁水波纹响应的界面 false不剪裁 如果控件是圆角不剪裁的话水波纹是矩形
                            containedInkWell: true,
                            //点击事件
                            onTap: () {
                              centerstop();
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                //color: Colors.deepOrange,
                                  borderRadius: BorderRadius.circular(100),
                                  boxShadow: [
                                    BoxShadow(
                                        offset: Offset(1, 1),//x,y轴
                                        color: Colors.deepOrange,//投影颜色
                                        blurRadius: 10//投影距离
                                    )
                                  ]

                              ),
                              //设置 child 居中
                              alignment: Alignment(0, 0),
                              height: 100.0,
                              width: 100,
                              child: Text("停止",style: TextStyle(fontSize: 15,fontWeight: FontWeight.w800,color: Colors.white),),
                            ),
                          ),
                        ),
                      ),

                  ),
                  SizedBox(height: 30,),
                     Container(
                      child: new Material(
                        color:Colors.transparent,
                        child: new Ink(
                          //设置背景
                          decoration: new BoxDecoration(
                            //背景
                            color: Colors.lightBlueAccent,
                            //设置四周圆角 角度
                            borderRadius: BorderRadius.all(Radius.circular(100.0)),
                            //设置四周边框
                            border: new Border.all(width: 3, color: Colors.blue),
                          ),
                          child: new InkResponse(
                            borderRadius: new BorderRadius.all(new Radius.circular(100.0)),
                            //点击或者toch控件高亮的shape形状
                            highlightShape: BoxShape.rectangle,
                            radius: 100.0,
                            //水波纹的颜色
                            splashColor: Colors.deepOrange,
                            //true表示要剪裁水波纹响应的界面 false不剪裁 如果控件是圆角不剪裁的话水波纹是矩形
                            containedInkWell: true,
                            //点击事件
                            onTap: () {
                              moderate();
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                //color: Colors.deepOrange,
                                  borderRadius: BorderRadius.circular(100),
                                  boxShadow: [
                                    BoxShadow(
                                        offset: Offset(1, 1),//x,y轴
                                        color: Colors.lightBlueAccent,//投影颜色
                                        blurRadius: 10//投影距离
                                    )
                                  ]

                              ),
                              //设置 child 居中
                              alignment: Alignment(0, 0),
                              height: 100.0,
                              width: 100,
                              child: Text("减速",style: TextStyle(fontSize: 15,fontWeight: FontWeight.w800,color: Colors.white),),
                            ),
                          ),
                        ),
                    ),
                  ),

                ],
              ),
            ),
          ),

      ),
    );
  }
}
